/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

package au.com.lastweekend.jim.imagebase;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

/**
 * I don't guarantee that every HashMap service will work.
 * 
 * @author grant@lastweekend.com.au
 * @version $Id: SoftHashMap.java,v 1.5 2006/03/01 09:52:03 ggardner Exp $
 * @param <K>
 * @param <V>
 */
public class SoftHashMap<K, V> extends AbstractMap<K, V> {

    private static final Logger LOG = Logger.getLogger(SoftHashMap.class);
    private SHMReferenceQueue _softReferenceQueue = new SHMReferenceQueue();
    private Map<K, SoftValue> _delegate = new HashMap<K, SoftValue>();

    /**
     * This only exists to cast the result to a SoftValue ReferenceQueue should itself be generic with poll returning <? super
     * Reference<? super T>> but I don't know if that is possible.
     */
    private class SHMReferenceQueue extends ReferenceQueue<V> {

        @SuppressWarnings("unchecked")
        @Override
        public SoftValue poll() {

            return (SoftValue) super.poll();
        }

    }

    private class SoftValue extends SoftReference<V> implements Map.Entry<K, V> {

        private K _key;

        public SoftValue(K key, V value, ReferenceQueue<? super V> queue) {

            super(value, queue);
            _key = key;
        }

        public K getKey() {

            return _key;
        }

        public V getValue() {

            return get();
        }

        public V setValue(V value) {

            throw new UnsupportedOperationException("No setting value after construction");
        }
    }

    @Override
    public V get(Object key) {

        SoftValue softValue = _delegate.get(key);
        if (softValue != null) {
            return softValue.get();
        } else {
            return null;
        }
    }

    @Override
    public V put(K key, V value) {

        clearQueue();
        V prev = get(key);
        SoftValue softValue = new SoftValue(key, value, _softReferenceQueue);
        _delegate.put(key, softValue);
        return prev;
    }

    /**
     * 
     */
    private void clearQueue() {

        SoftValue sv;
        while ((sv = _softReferenceQueue.poll()) != null) {
            K key = sv.getKey();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Reclaiming soft reference with key = " + key);
            }
            remove(key);
        }

    }

    @Override
    public Set<Entry<K, V>> entrySet() {

        clearQueue();

        return new HashSet<Entry<K, V>>(_delegate.values());
    }

    @Override
    public V remove(Object key) {

        SoftValue removed = _delegate.remove(key);
        if (removed != null) {
            return removed.getValue();
        }
        return null;
    }

}